import { defineStore } from 'pinia'

import { reqLogin, reqrouters } from '@/api/user/index'
import { constantRoute, asnycRoute } from '@/router/routes'
import { UserState } from './types/type'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'

function filterAsyncRoute(asnycRoutes: any, routes: any) {
  return asnycRoutes.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}

const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      menuRoutes: constantRoute,
    }
  },

  actions: {
    async userLogin(data: any) {
      let result: any = await reqLogin(data)
      if (result.code == 200) {
        localStorage.setItem('TOKEN', JSON.stringify(result.data.token))
        localStorage.setItem('ROUTERS', JSON.stringify(result.data.routes))
        this.getroutess(result.data.routes)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    getroutess(res: any) {
      const userAsyncRoute = filterAsyncRoute(cloneDeep(asnycRoute), res)
      this.menuRoutes = [...constantRoute, ...userAsyncRoute]
      ;[...userAsyncRoute].forEach((route: any) => {
        router.addRoute(route)
      })
    },
  },
  getters: {},
  persist: {
    enabled: true, // 这个配置代表存储生效，而且是整个store都存储
  },
})
//对外暴露获取小仓库方法
export default useUserStore
